/**
 * 食药公用js
 *
 * */
define([
    'base',
    'msgTool',
    'bootstrapDialog',
    'laydate',
    'bootstrapTable',
    'highcharts',
    'exporting',
    'highchartsCN',
    'sandSignika',
    'jqViewer',
    'jqPrint',
    'plugins/wangEditor/wangEditor.min',
    'css!global/plugins/wangEditor/wangEditor.min.css',
    'plugins/fileInput/fileinput.min',
    'css!global/plugins/fileInput/fileinput.min.css',
    "css!global/plugins/viewer/viewer.min.css"
], function (base, msgTool, BootstrapDialog, laydate, _, highcharts, _, _, _, _, jqPrint, E,_) {
    //默认加载基础库
    base();
    return {
        list: function () {
            var myTable = $('#dataList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'list.json'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: 'list.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    window.location.href = row.id;
                },
                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '轮播图',
                        nameValue: row.title,
                        url: '../status/action'
                    })
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '轮播图',
                        nameValue: row.title,
                        url: '../delete/action'
                    });
                }
            };


            //table表格
            myTable.bootstrapTable({
                url: 'list.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [
                    {
                        field: 'id',
                        title: '编号',
                        align: 'center',
                        width: '5%'
                    }, {
                        field: 'title',
                        title: '轮播图名称',
                        width: '30%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-hashtag text-primary" aria-hidden="true"></i>&emsp;<b>' + value
                        }
                    },
                    {
                        field: 'type',
                        title: '类型',
                        align: 'center',
                        width: '10%',
                        formatter: function (value, row, index) {
                            var result = "未知";
                            switch (value) {
                                case 1:
                                    result = "PC端";
                                    break;
                                case 2:
                                    result = "手机端";
                                    break;
                                case 3:
                                    result = "其他";
                                    break;
                                default:
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'description',
                        title: '备注',
                        width: '20%',
                        align: 'center'
                    },
                    {
                        field: 'createTime',
                        title: '创建时间',
                        align: 'center',
                        width: '10%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-clock-o" aria-hidden="true"></i>&emsp;' + value;
                        }
                    },
                    {
                        field: 'status',
                        title: '状态',
                        width: '10%',
                        align: 'center',
                        formatter: function (value, row, index) {
                            var result = "";
                            switch (value) {
                                case 0:
                                    result = "<span class=\"label label-danger\"><i class=\"fa fa-lock\" aria-hidden=\"false\"></i>&nbsp;禁用</span>";
                                    break;
                                case 1:
                                    result = "<span class=\"label label-primary\"><i class=\"fa fa-unlock\" aria-hidden=\"true\"></i>&nbsp;启用</span>";
                                    break;
                                default:
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        width: '10%',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

            //搜索刷新
            $('#search-btn').on('click', function () {
                tableRefresh();
            });


            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.itemName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '轮播图',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.titleSearch = $("#titleSearch").val();
                params.typeSearch = $("#typeSearch").val();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    type: params.typeSearch,
                    search: params.titleSearch//标题模糊搜
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }

        },
        view: function () {


        },

        save: function () {

            
			//轮播图
			doUploader("#userImgUploader", "请选择轮播图图片", "#userImg-upload-error", "#userImg-upload-success", "userImg");


			function doUploader(node, placeholder, elErrorContainer, successContainer, listName) {
				return $(node).fileinput({
					//设置语言
					language: 'zh',
					//上传的地址
					uploadUrl: '/common/uploader/index',
					method: 'post',
					msgPlaceholder: placeholder,
					//附加属性(0图片，1文件)
					uploadExtraData: {filesType: 0},
					//上传类型
					allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg'],
					//是否显示图片展示框
					showPreview: false,
					//是否显示上传按钮
					showUpload: true,
					showCancel: false,
					//是否显示上传输入框
					showCaption: true,
					//是否显示删除键
					showRemove: true,
					//浏览图标
					browseIcon: '<i class="iconfont icon-wenjianjia"></i>&nbsp;',
					//浏览样式
					browseClass: 'btn btn-success btn-outline',
					//上传图标
					uploadIcon: '<i class="iconfont icon-upload"></i>&nbsp;',
					//上传样式
					uploadClass: 'btn btn-success btn-outline',
					//移除图标
					removeIcon: '<i class="iconfont icon-remove"></i>&nbsp;',
					//移除样式
					removeClass: 'btn btn-info btn-outline',
					//单位为kb，(30M)如果为0表示不限制文件大小
					maxFileSize: 10720,
					//错误显示位置
					elErrorContainer: elErrorContainer,
					//错误显示位置节点样式
					msgErrorClass: 'alert alert-block alert-danger',
					//验证数量
					validateInitialCount: true
				}).on("fileuploaded", function (event, data) {
					console.log(data)
					if (data.response !== null && data.response.status) {
						$("#photo").attr("src",data.response.domain+data.response.url);
						$("#cover").val(data.response.url);
					} else {
						$(elErrorContainer).text(data.response.message);
					}
				});
			}


		
            /**
             * 验证
             *
             */

            $("#itemForm").validate({
                rules: {
                    title: {
                        required: true
                    },
                    matterNature: {
                        required: true
                    },
                    cateId: {
                        required: true
                    },
                    legalTerm: {
                        required: true
                    },
                    promiseTerm: {
                        required: true
                    },
                    approvalUnit: {
                        required: true
                    },
                    address: {
                        required: true
                    },
                    phone: {
                        required: true
                    },
                    officeTime: {
                        required: true
                    },
                    link: {
                        required: true
                    },
                    sort: {
                        required: true
                    }
                },
                messages: { //自定义验证消息
                    title: {
                        required: "请输入事项名称"
                    },
                    matterNature: {
                        required: "请输入事项性质"
                    },
                    cateId: {
                        required: "请输入事项分类"
                    },
                    legalTerm: {
                        required: "请输入法定时限"
                    },
                    promiseTerm: {
                        required: "请输入承诺期限"
                    },
                    approvalUnit: {
                        required: "请输入审批主体"
                    },
                    address: {
                        required: "请输入办公地址"
                    },
                    phone: {
                        required: "请输入联系电话"
                    },
                    officeTime: {
                        required: "请输入办公时间"
                    },
                    link: {
                        required: "请输入事项链接"
                    },
                    sort: {
                        required: "请输入事项排序"
                    }
                }
            });

            //保存
            $('#doSubmit').on('click', function () {
                var valid = $("#itemForm").validate().form();
                if (valid) {
                    $.ajax({
                        url: '../save/action',
                        type: 'POST',
                        data: $('#itemForm').serialize(),
                        dataType: "JSON",
                        success: function (data) {
                            if (data.success) {
                                msgTool.success("保存成功！");
                                setTimeout(function () {
                                window.location.href="index";	
                                }, 3000);  
                                
                            } else {
                                msgTool.error("保存失败！");
                            }
                        },
                        error: function (error) {
                            msgTool.error("操作失败，请刷新当前页面后重试！");
                        }
                    });
                }
            });



        }
    }
});






